import session from 'koa-session'

function recursiveTrim(data) {
  if (data && data.trim) return data.trim()
  return data
}

export async function trimBodyParams(ctx, next) {
  let body = ctx.request.body
  if (body) {
    for (const iterator in body) {
      if (body.hasOwnProperty(iterator)) {
        body[iterator] = recursiveTrim(body[iterator])
      }
    }
  }
  await next()
}

// 设置session
export async function setSession(app) {
  const config = {
    key: 'koa.sess',
    //有效期
    maxAge: 1000 * 60 * 20,
    //刷新之后刷新 maxAge
    rolling: true,
    renew: true
  }
  return session(config, app)
}
